package com.example.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.Bean.*;
import com.example.demo.Mapper.*;
import com.example.demo.Utils.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ExperimentStuService {


    @Autowired
    ExperimentStuMapper experimentStuMapper;
    @Autowired
    StudentClassMapper studentClassMapper;

    @Autowired
    ReportMapper reportMapper;

    @Autowired
    BelongMapper belongMapper;

    @Autowired
    TeamMapper teamMapper;

    @Autowired
    TeamExperimentMapper teamExperimentMapper;


    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    public Result searchExperimentStu(String name,String studentUid,Integer pageNum,Integer pageSize) throws Exception{
        Result result = null;
            List<Integer> studentGroups = new ArrayList<>();
            List<Belong> belongs = belongMapper.selectList(new QueryWrapper<Belong>().eq("student_uid", studentUid));
            for (Belong belong : belongs) {
                studentGroups.add(belong.getGroupId());
            }
            if (studentGroups.size() == 0){
                return new Result(200, "未找到相关实验！");
            }
            List<Integer> experimentIds = new ArrayList<>();
            List<TeamExperiment> teamExperiments = teamExperimentMapper.selectList(new QueryWrapper<TeamExperiment>().in("group_id", studentGroups));
            for (TeamExperiment teamExperiment : teamExperiments) {
                experimentIds.add(teamExperiment.getExperimentId());
            }
            if(teamExperiments.size() == 0){
                return new Result(200, "未找到相关实验！");
            }
            HashMap res = new HashMap();
            Page<Experiment> page = new Page<>(pageNum,pageSize);
//            List ids = new ArrayList();
//            for (StudentClass studentClass : studentClasses) {
//                ids.add(studentClass.getCourseId());
//            }
//            if(ids.size() == 0){
//                ids.add("no found");
//            }
            page = experimentStuMapper.selectPage(page,new QueryWrapper<Experiment>().like("name",name).and(wrapper -> {wrapper.in("experiment_id",experimentIds);}));
            List<Experiment> experiments= page.getRecords();
            res.put("page",pageNum);
            res.put("size",pageSize);
            Integer total = experimentStuMapper.selectCount(new QueryWrapper<Experiment>().like("name",name).and(wrapper -> {wrapper.in("experiment_id",experimentIds);}));
            res.put("total",total);
            res.put("totalPage",total%pageSize>=1 ? total/pageSize+1 : total/pageSize);
            if (experiments.size()==0) {
                return new Result(200, "未找到相关实验！");
            }
            for (Experiment experiment : experiments) {
                experiment.setStates(((Integer)getStatus(studentUid,experiment.getExperimentId()).getObj()) == 0 ? "未提交" : "已提交");
                experiment.setComment(getReportComment(studentUid,experiment.getExperimentId()));
                experiment.setCode((Float)getReportCode(studentUid,experiment.getExperimentId()).getObj());
            }
            res.put("list",experiments);
            result = new Result(200,res);
        return result;
    }

    public Result getTotalExperimentStuNum(String studentId) throws Exception{
        Result result = null;
            List<Integer> studentGroups = new ArrayList<>();
            List<Belong> belongs = belongMapper.selectList(new QueryWrapper<Belong>().eq("student_uid", studentId));
            for (Belong belong : belongs) {
                studentGroups.add(belong.getGroupId());
            }
            List<Integer> experimentIds = new ArrayList<>();
            List<TeamExperiment> teamExperiments = teamExperimentMapper.selectList(new QueryWrapper<TeamExperiment>().in("group_id", studentGroups));
            for (TeamExperiment teamExperiment : teamExperiments) {
                experimentIds.add(teamExperiment.getExperimentId());
            }
            Integer num = experimentStuMapper.selectCount(new QueryWrapper<Experiment>().in("experiment_id",experimentIds));
            result = new Result(200, num);
        return result;
    }

    public Result getStatus(String studentUid,Integer experimentId) throws Exception{
        Result result = null;
            HashMap<String,Object> map = new HashMap<>();
            map.put("student_uid",studentUid);
            map.put("experiment_id",experimentId);
            Report report = reportMapper.selectOne(new QueryWrapper<Report>().allEq(map));
            if(report!=null){
                result = new Result(200,1);
            }else{
                result = new Result(200,0);
            }
        return result;
    }

    public Result getExperimentStuPage(Integer pageNum,Integer pageSize,String studentUid) throws Exception{
        Result result = null;
            Map<String,Object> res = new HashMap<>();
            res.put("size",pageSize);
            res.put("page",pageNum);
            Integer total = (Integer)getTotalExperimentStuNum(studentUid).getObj();
            res.put("total",total);
            res.put("totalPage",total%pageSize>=1 ? total/pageSize+1 : total/pageSize);
            Page<Experiment> page = new Page<>(pageNum, pageSize);
            page = experimentStuMapper.selectPage(page, new QueryWrapper<Experiment>().eq("course_id",studentClassMapper.selectOne(new QueryWrapper<StudentClass>().eq("student_uid",studentUid)).getCourseId()));
            res.put("list",page.getRecords());
            result = new Result(200, res);
        return result;
    }

    public List<Experiment> getExperimentList(String courseId) throws Exception{
        List<Experiment> experiments = null;
        experiments = experimentStuMapper.selectList(new QueryWrapper<Experiment>().eq("course_id", courseId));
        return experiments;
    }

    public Result getReportCode(String studentUid,Integer experimentId) throws Exception{
        Result result = null;
            HashMap<String,Object> map = new HashMap<>();
            map.put("student_uid",studentUid);
            map.put("experiment_id",experimentId);
            Report report = reportMapper.selectOne(new QueryWrapper<Report>().allEq(map));
            if(report!=null){
                result = new Result(200,report.getCode());
            }else{
                result = new Result(200,"未找到实验分数！");
            }
        return result;
    }

    public Result getReportStu(String studentUid,Integer experimentId) throws Exception{
        Result result = null;
            HashMap<String,Object> map = new HashMap<>();
            map.put("student_uid",studentUid);
            map.put("experiment_id",experimentId);
            Report report = reportMapper.selectOne(new QueryWrapper<Report>().allEq(map));
            if(report!=null){
                result = new Result(200,report);
            }else{
                result = new Result(200,"未找到报告！");
            }
        return result;
    }

    private String getReportComment(String studentUid, Integer experimentId) throws Exception{
            HashMap<String,Object> map = new HashMap<>();
            map.put("student_uid",studentUid);
            map.put("experiment_id",experimentId);
            Report report = reportMapper.selectOne(new QueryWrapper<Report>().allEq(map));
            if(report==null){
                return null;
            }else{
                return report.getComment();
            }
    }

    public Result uploadReport(MultipartFile file, Integer experimentId, Student student) throws Exception{
        Result result = null;
            String originName = file.getOriginalFilename();
            if(!originName.endsWith(".pdf")){
                result = new Result(403,"请上传pdf文件！");
            }else{
                String url = FileUtil.uploadFile(file);
                Report report = new Report();
                report.setClasses(student.getClasses());
                report.setExperimentId(experimentId);
                report.setName(student.getName());
                report.setPath(url);
                report.setStudentUid(student.getStudentUid());
                report.setUploadTime(new Date());
                if(reportMapper.selectCount(new QueryWrapper<Report>().eq("experiment_id",report.getExperimentId()).eq("student_uid",report.getStudentUid())) <= 0) {
                    if (reportMapper.insert(report) > 0) {
                        return new Result(200, url);
                    }
                }else {
                    reportMapper.update(report,new UpdateWrapper<Report>().eq("experiment_id",report.getExperimentId()).eq("student_uid",report.getStudentUid()));
                    return new Result(200, url);
                }
            }
        return result;
    }

}
